// pages/submit/index.js
const app = getApp()
wx.cloud.init({
  traceUser: true
})
const db = wx.cloud.database()
const voice = db.collection('voice')
const savedvoice = db.collection('savedvoice')

let clickFlag = false
let clickSaveFlag = false
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 页面的初始数据
   */
  properties: {
    saveId: {
      type: String
    },
    isSave: {
      type: Boolean,
      value: false
    }
  },
  observers: {
    'saveId': function (saveId) {
      if (saveId != '') {
        wx.showLoading({
          title: '加载中',
          mask: true,
        })
        savedvoice.doc(saveId).get().then(res => {
          wx.hideLoading()
          this.setData({
            coverImg: res.data.coverImg,
            src: res.data.coverImg == '' ? 'https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/选择图片加号.jpeg?sign=2033b71e6fecfd5a575b567152e138a4&t=1560848219' : res.data.coverImg,
            voiceContent: res.data.voiceContent,
            srcState: '1'
          })
          this.editorCtx.setContents({
            html: res.data.voiceContent
          })
        })
      }
    },
    'isSave': function (isSave) {
      if (isSave){
        this.handleSave()
        // console.log('保存')
      }
    }
  },
  data: {
    loadModal: false,
    src: "https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/选择图片加号.jpeg?sign=2033b71e6fecfd5a575b567152e138a4&t=1560848219",
    srcState: '',
    voiceContent: '<p><br></p>',
    coverImg: ''
  },
    
  
  methods: {
    gotoShow(){
      var _this = this
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          _this.setData({
            src: res.tempFilePaths,
            srcState: '1',
            coverImg: res.tempFilePaths[0]
          })
        }
      })
    },
    onEditorReady(){
      const that = this
      this.createSelectorQuery().select('#editor').context(function (edit) {
        that.editorCtx = edit.context
      }).exec()
    },
    submitVoice(){
      if (this.data.voiceContent == '<p><br></p>') return
      if (clickSaveFlag) return
      if (clickFlag) return //防抖处理
      else clickFlag = true
      this.setData({
        loadModal: true
      })
      if (this.properties.saveId!=''){
        wx.cloud.callFunction({
          name: 'deleteSavedVoice',
          data: {
            voiceId: this.properties.saveId,
            state: typeof (this.data.coverImg) == typeof (this.data.src) ? 'notDeleteImg' : ''
          }
        })
      }
        wx.cloud.callFunction({
          name: 'submitVoice',
          data: {
            voiceContent: this.data.voiceContent,
            coverImg: typeof (this.data.coverImg) == typeof (this.data.src) ? this.data.coverImg : ''
          }
        }).then(res => {
          if (this.data.coverImg != '' && (typeof (this.data.coverImg) != typeof (this.data.src))){
            wx.cloud.uploadFile({
              cloudPath: 'userVoice/' + res.result.voiceId,
              filePath: this.data.coverImg, // 文件路径
            }).then(res1 => {
              voice.doc(res.result.voiceId).update({
                data: {
                  coverImg: res1.fileID
                }
              }).then(res2 => {
                this.setData({
                  loadModal: false
                })
                clickFlag = false
                this.triggerEvent('setRefresh', true)
                app.sumCount = {}
                wx.showToast({
                  title: '发布成功',
                  icon: 'success',
                  duration: 2000
                })
                this.setData({
                  // voiceContent: '<p><br></p>',
                  src: "https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/选择图片加号.jpeg?sign=2033b71e6fecfd5a575b567152e138a4&t=1560848219",
                  srcState: '',
                  coverImg: ''
                })
                  
                this.editorCtx.clear()
              }).catch(err2 => {
                console.log(err2)
              })
            }).catch(err1 => {
              console.log(err1)
            })
          }else{
            this.setData({
              loadModal: false,
              src: "https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/选择图片加号.jpeg?sign=2033b71e6fecfd5a575b567152e138a4&t=1560848219",
              srcState: '',
              coverImg: ''
            })
            clickFlag = false
            this.triggerEvent('setRefresh', true)
            app.sumCount = {}
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              duration: 2000
            })
            this.editorCtx.clear()
          }
        }).catch(err => {
          console.log(err)
        })
    },
    handleSave(){
      if (this.data.voiceContent == '<p><br></p>') return
      if (clickFlag) return
      if (clickSaveFlag) return //防抖处理
      else clickSaveFlag = true
      this.setData({
        loadModal: true
      })
      if (this.properties.saveId!=''){
        wx.cloud.callFunction({
          name: 'deleteSavedVoice',
          data: {
            voiceId: this.properties.saveId,
            state: typeof (this.data.coverImg) == typeof (this.data.src) ? 'notDeleteImg' : ''
          }
        }).then(res => {
          this.saveVoice()
        })
      }else{
        savedvoice.where({
          _openid: app.user._openid
        }).count().then(count => {
          if (count.total >= 10) {
            wx.showToast({
              title: '暂存区已满10条',
              duration: 2000
            })
            return
          } else {
            this.saveVoice()
          }
        })
      }
    },
    saveVoice(){
      wx.cloud.callFunction({
        name: 'saveVoice',
        data: {
          voiceContent: this.data.voiceContent,
          coverImg: typeof(this.data.coverImg) == typeof(this.data.src) ? this.data.coverImg : ''
        }
      }).then(res => {
        // console.log(this.data.src)
        // console.log(this.data.coverImg)
        if (this.data.coverImg != '' && (typeof (this.data.coverImg) != typeof (this.data.src))) {
          wx.cloud.uploadFile({
            cloudPath: 'userVoice/' + res.result.voiceId,
            filePath: this.data.coverImg, // 文件路径
          }).then(res1 => {
            // console.log(res1.fileID)
            savedvoice.doc(res.result.voiceId).update({
              data: {
                coverImg: res1.fileID
              }
            }).then(res2 => {
              this.setData({
                loadModal: false
              })
              clickSaveFlag = false
              // this.triggerEvent('setRefresh', true)
              app.sumCount = {}
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
              this.setData({
                // voiceContent: '<p><br></p>',
                src: "https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/选择图片加号.jpeg?sign=2033b71e6fecfd5a575b567152e138a4&t=1560848219",
                srcState: '',
                coverImg: ''
              })

              this.editorCtx.clear()
            }).catch(err2 => {
              console.log(err2)
            })
          }).catch(err1 => {
            console.log(err1)
          })
        } else {
          this.setData({
            loadModal: false,
            src: "https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/选择图片加号.jpeg?sign=2033b71e6fecfd5a575b567152e138a4&t=1560848219",
            srcState: '',
            coverImg: ''
          })
          clickSaveFlag = false
          // this.triggerEvent('setRefresh', true)
          app.sumCount = {}
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
          })
          this.editorCtx.clear()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleInput(e){
      this.setData({
        voiceContent: e.detail.html
      })
      if (e.detail.html == '<p><br></p>'){
        this.triggerEvent('showSaveModal', false)
      }else{
        this.triggerEvent('showSaveModal', true)
      }
    }
  },

  detached: function(){
    // console.log('22')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  created: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})